package edu.siu.math.egut.main;

import java.util.Arrays;
import java.util.regex.Pattern;

import edu.siu.math.egut.util.NoSuchElementException;
import edu.siu.math.egut.util.Unipotent;
import edu.siu.math.egut.util.UnipotentReadException;

public class Conjugate {

    private static final String NO_BY_INSTRUCTIONS = "Format should be \"Conjugate <Sunipotents> by < group elements >\"";
    private static final String BAD_SUNIS_BEFORE_THE_BY_MESSAGE = "Arguments given prior to the \"by\" could not be read into a unipotent.";
    private static final String BAD_ELEMENTS_AFTER_THE_BY_MESSAGE = "Bad arguments after the \"by\".";
    public static void main(String[] args) {
	
	String [] input = args;//edu.siu.math.egut.io.Algorithms.getInput(args);
	
	// FIXME This produces incorrect results when (x_a(r), x_{-a}(s) ) arises.
	// TODO add functionality for conjugating by the inverse.
	
	// find the "by"
	int by = findBy(input);
	if(by == -1){
	    System.out.print(NO_BY_INSTRUCTIONS);
	    System.exit(1);
	}
	try {
	    Unipotent u = Unipotent.read(Arrays.copyOfRange(input, 0, by));
	    for(int i = input.length -1 ; i > by; i--)
	    {
		u.actBy(input[i]);
		
	    }
	    printResult(input,by, u);
	    
	} catch (UnipotentReadException e) {

	    System.out.println(BAD_SUNIS_BEFORE_THE_BY_MESSAGE);
	    System.exit(1);
	} catch (NoSuchElementException e) {
	    System.out.println(BAD_ELEMENTS_AFTER_THE_BY_MESSAGE);
	    System.exit(1);

	
	}
		
    }
    private static void printResult(String[] args, int by, Unipotent u) {
	StringBuilder sb = new StringBuilder(args[by+1]);
	for( int i = by+2; i < args.length; i++)
	    sb.append(" "+args[i]);
	String a= sb.toString();
	sb.append(" * ");
	for( int i = 0 ; i < by; i++)
	    sb.append(args[i]);
	sb.append(" * ("+a+")^{-1}=");
	System.out.println(sb.toString()+"\n"+u.toString()+"\n\n");
	
	
    }
    private static int findBy(final String[] args){
	int by = 0;
	while( by < args.length){
	    if(Pattern.compile("by", Pattern.CASE_INSENSITIVE).matcher(args[by]).matches())
		return by;
	    by++;
	}
	return -1;

    }
}
